import {
  deleteSysOperLogUsingPost,
  listSysOperLogByPageUsingPost,
} from '@/services/api/sysOperLogController';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import {
  Button,
  Collapse,
  Descriptions,
  Divider,
  message,
  Modal,
  Popconfirm,
  Space,
  Tag,
} from 'antd';
import React, { useRef, useState } from 'react';
import { Panel } from 'rc-collapse';

/**
 * 系统操作日志页面
 *
 * @constructor
 */
const SysOperLogPage: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const [openDetail, setOpenDetail] = useState<boolean>(false);
  const [currentData, setCurrentData] = useState<API.SysOperLog>({});

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.SysOperLog) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteSysOperLogUsingPost({
        id: row.operId as any,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.SysOperLog>[] = [
    {
      title: 'ID',
      dataIndex: 'operId',
      valueType: 'text',
      hideInForm: true,
      align: 'center',
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '操作时间(毫秒)',
      dataIndex: 'costTime',
      valueType: 'text',
      align: 'center',
      render: (_, record) => <>{record.costTime + ' ms'}</>,
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      valueType: 'text',
      align: 'center',
    },
    {
      title: 'IP',
      dataIndex: 'operIp',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '请求类型',
      dataIndex: 'requestMethod',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '登录地址',
      dataIndex: 'loginLocation',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '错误提示',
      dataIndex: 'errorMsg',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '成功',
        },
        1: {
          text: '失败',
        },
      },
      align: 'center',
    },
    {
      title: '操作时间',
      sorter: true,
      dataIndex: 'operTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              setCurrentData(record);
              setOpenDetail(true);
            }}
          >
            详情
          </Button>
          <Popconfirm
            title="删除数据"
            description="您确定要删除此数据吗？"
            onConfirm={() => handleDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const businessTypeMap = {
    0: '其它',
    1: '新增',
    2: '修改',
    // ...其他业务类型
  };

  // 状态标签映射
  const statusMap = {
    0: <Tag color="success">成功</Tag>,
    1: <Tag color="error">失败</Tag>,
  };

  return (
    <div>
      <PageContainer>
        <ProTable<API.SysOperLog>
          headerTitle={'查询表格'}
          actionRef={actionRef}
          rowKey="key"
          search={{
            labelWidth: 120,
          }}
          pagination={{
            pageSize: 10,
          }}
          request={async (params, sort, filter) => {
            let sortField = Object.keys(sort)?.[0];
            let sortOrder = sort?.[sortField] ?? undefined;

            if (sortField === undefined && sortOrder === undefined) {
              sortField = 'operTime';
              sortOrder = 'descend';
            }

            const { data, code } = await listSysOperLogByPageUsingPost({
              ...params,
              sortField,
              sortOrder,
              ...filter,
            } as API.SysUserLoginRequest);

            return {
              success: code === 0,
              data: data?.records || [],
              total: Number(data?.total) || 0,
            };
          }}
          columns={columns}
        />
      </PageContainer>
      <Modal
        title="操作日志详情"
        width={800}
        open={openDetail}
        onCancel={() => {
          setOpenDetail(false);
        }}
        footer={null}
        destroyOnClose
      >
        <Descriptions bordered column={2}>
          <Descriptions.Item label="日志ID">{currentData.operId || '-'}</Descriptions.Item>
          <Descriptions.Item label="操作账号">{currentData.userAccount || '-'}</Descriptions.Item>
          <Descriptions.Item label="操作类型">
            {businessTypeMap[currentData.businessType as keyof typeof businessTypeMap] || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="操作状态">
            {currentData.status !== undefined
              ? statusMap[currentData.status as keyof typeof statusMap]
              : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="操作IP">{currentData.operIp || '-'}</Descriptions.Item>
          <Descriptions.Item label="操作地点">{currentData.operLocation || '-'}</Descriptions.Item>
          <Descriptions.Item label="耗时(ms)">
            {currentData.costTime + ' ms' || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="操作时间">{currentData.operTime || '-'}</Descriptions.Item>
        </Descriptions>

        <Divider orientation="left">请求信息</Divider>
        <Descriptions bordered column={1}>
          <Descriptions.Item label="请求类型">{currentData.requestMethod || '-'}</Descriptions.Item>
          <Descriptions.Item label="请求URL">{currentData.operUrl || '-'}</Descriptions.Item>
          <Descriptions.Item label="请求方法">{currentData.method || '-'}</Descriptions.Item>
        </Descriptions>

        <Collapse ghost>
          <Panel header="请求参数" key="1">
            <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto' }}>
              {currentData.operParam
                ? JSON.stringify(JSON.parse(currentData.operParam), null, 2)
                : '无'}
            </pre>
          </Panel>
          <Panel header="返回结果" key="2">
            <pre style={{ margin: 0, maxHeight: 200, overflow: 'auto' }}>
              {currentData.jsonResult
                ? JSON.stringify(JSON.parse(currentData.jsonResult), null, 2)
                : '无'}
            </pre>
          </Panel>
          {currentData.errorMsg && (
            <Panel header="错误信息" key="3">
              <div style={{ color: 'red' }}>{currentData.errorMsg}</div>
            </Panel>
          )}
        </Collapse>
      </Modal>
    </div>
  );
};
export default SysOperLogPage;
